import { bindAccountOrganization, bindAccountQueryByPhone, currentAccount, loginWxampForWechatBindAccount, loginWxampForWechatBindingAccount } from "../../../service/api/api-login";
import access from "../../../utils/access";
import { loginCallback } from "../../../utils/loginUtils";

// pages/user/bind/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoading: false,//节流阀
    bindState: 0,//状态organizations
    phone: '',// 手机号
    name: '',// 姓名
    organizations: [],// 组织列表
    organization: undefined,// 已选的组织
    noticeBarMessage: {//toolbar、顶部公告栏、提交按钮
      toolbarTitle: "",
      theme: "",
      content: "",
      submitText: "",
    },
    selectVisible: false,//是否显示选择
    helpVisible: false,//是否显示帮助
    note: '',//显示已选择的单位
    bindOrganizations: [],
    imageSrc: '/image/qr/qr-wechat-13220207320(已去底).jpg',//管理员微信图片
    bindStep: 0,//绑定步骤
    unitList: [{
      visible: false,
      organizations: [],
      organizationIds: []
    }],//单位列表
    disabledPhone: false,//手机号码是否可修改
  },

  //复制联系方式
  copyContent(e: any) {
    wx.setClipboardData({
      data: "13220207320",
      success: function (res) {
        wx.showToast({
          title: '微信：13220207320',
          icon: "none",
          duration: 1500
        })
      }
    });
  },
  //复制联系方式
  makePhoneCall(e: any) {
    wx.makePhoneCall({
      phoneNumber: '13220207320' //仅为示例，并非真实的电话号码
    })
  },
  //滑动单位删除
  onDelete(e) {
    let index = e.currentTarget.dataset.index
    this.data.unitList.splice(index, 1)
    this.setData({
      unitList: this.data.unitList
    })
  },
  showNewUnitSelection() {
    this.data.unitList.push({
      visible: false,
      organizations: [],
      organizationIds: []
    })
    this.setData({
      unitList: this.data.unitList
    })
  },
  newUnitChange(event) {
    const selectedUnit = event.detail.value;
    // 处理新增单位的选择操作
    // 隐藏新增单位选择框
    this.setData({
      showNewUnit: false
    })
  },
  //显示联系管理员页面
  showHelp() {
    this.setData({
      helpVisible: !this.data.helpVisible
    })
  },
  //输入手机号
  onPhoneInput(e) {
    // 取出实时的变量值
    let phone = e.detail.value;
    this.setData({
      phone
    })
  },
  //输入名字
  onNameInput(e) {
    // 取出实时的变量值
    let name = e.detail.value;
    this.setData({
      name
    })
  },

  async onLoad() {
    this.onLoadAlertMessage();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.hideHomeButton();
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
    })
  },
  /**
   * 预备Tree结构数据
   * @param data
   */
  readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = [];
    if (data) {
      data.forEach((val) => {
        if (val.isFolder === 1 && val.children === undefined) {
        } else {
          treeData.push({
            label: val.name,
            value: val.id,
            isFolder: val.isFolder,
            // disabled: val.isFolder === 1 && val.children === undefined ? 0 : 1,
            isChildren: val.children === undefined ? 0 : 1,
            children: val.children === undefined ? null : this.readyTreeData(val.children as AdminOrganizationData.Organization[]),
          });
        }
      });
    }
    return treeData;
  },
  //显示选择
  showCascader(e) {
    const index = e.target.dataset.index;
    this.data.unitList[index].visible = true
    this.setData({
      unitList: this.data.unitList
    })
  },
  onLoadAlertMessage() {
    const bindStep = this.data.bindStep;
    const bindState = this.data.bindState;

    let noticeBarMessage = this.data.noticeBarMessage;
    if (bindStep == 0) {
      noticeBarMessage = {
        toolbarTitle: "查询",
        theme: "info",
        content: "请填写手机号，查询账户状态",
        submitText: "查询"
      };
    } else if (bindStep == 1 && bindState == 0) {
      noticeBarMessage = {
        toolbarTitle: "注册",
        theme: "info",
        content: "填写所有信息，提交后待管理员审核完成注册流程",
        submitText: "注册"
      }
    } else if (bindStep == 1 && bindState == 1) {
      noticeBarMessage = {
        toolbarTitle: "绑定",
        theme: "success",
        content: "管理员已为您添加好了账户，点击下方按进入首页",
        submitText: "绑定"
      }
    } else if (bindStep == 1 && bindState == 3) {
      noticeBarMessage = {
        toolbarTitle: "账号未启用",
        theme: "warring",
        content: "管理员已为您添加好了账户，点击下方按进入首页",
        submitText: "进入首页"
      }
    } else if (bindStep == 1 && bindState == 4) {
      noticeBarMessage = {
        toolbarTitle: "绑定",
        theme: "success",
        content: "管理员已为您添加好了账户，点击下方按进入首页",
        submitText: "进入首页"
      }
    }
    this.setData({
      noticeBarMessage: noticeBarMessage
    })
  },
  /**
   * 点击事件 绑定账户（登录）
   */
  onFormSubmitBind() {
    let that = this;
    // 校验手机号码
    if (!new RegExp(/^1\d{10}$/).test(this.data.phone)) {
      wx.showToast({
        title: '手机号输入有误，请重新输入',
        icon: 'none',
        duration: 1500
      })
      return
    }
    that.setData({ isLoading: true });
    wx.showLoading({
      title: this.data.noticeBarMessage.submitText + '中...'
    })
    wx.showNavigationBarLoading();
    let bindStep = this.data.bindStep
    if (bindStep === 0) {
      bindAccountQueryByPhone({
        phone: that.data.phone,
      }).then(async (response) => {
        let bindState = response.data.bindState
        if (bindState === 0) {
          await bindAccountOrganization().then(res => {
            if (res.data) {
              this.setData({
                organizations: Array.isArray(res.data) && this.readyTreeData(res.data) || [],
                disabledPhone: true
              })
            }
          })
        } else {
          this.onLoadAlertMessage();
        }
        this.setData(
          { bindState: bindState, isLoading: false, disabledPhone: true }
        )
        this.onLoadAlertMessage();
        wx.hideNavigationBarLoading();
        wx.hideLoading();
      })
    } else {
      if (this.data.bindState === 0) {
        if (this.data.name === undefined || this.data.name === "") {
          wx.showToast({
            title: '请输入姓名',
            icon: 'none',
            duration: 1500
          })
          return
        }
        if (this.data.unitList[0].organizations === undefined) {
          wx.showToast({
            title: '请选择组织',
            icon: 'none',
            duration: 1500
          })
          return
        }
        const ids = this.data.unitList.map((item) => {
          return item.organizationIds.toString()
        })
        const idsSet = new Set(ids);
        if ([...idsSet].length !== ids.length) {
          wx.showToast({
            title: '请不要重复选择相同单位',
            icon: 'none',
            duration: 1500
          })
          return;
        }
      }
      wx.login({
        success: loginRes => {
          const idList = this.data.unitList.map((item) => {
            return { organizationIds: item.organizationIds }
          })
          loginWxampForWechatBindAccount({
            serviceName: "xtbs",
            code: loginRes.code,
            phone: that.data.phone,
            name: that.data.name,
            bindOrganizations: idList,
          }).then(async (response) => {

            const { state, satoken, accountId } = response.data;

            if (this.data.bindStep == 1 && this.data.bindState == 0 && state == 2) {
              //跳转到状态页面：注册成功，请等待管理员审核
              wx.reLaunch({
                url: `/pages/user/state/index?state=${state}`
              })
            } else if (this.data.bindStep == 1 && this.data.bindState == 1 && state == 2) {
              wx.reLaunch({
                url: `/pages/user/state/index?state=${state}`
              })
            } else if (this.data.bindStep == 1 && state == 4) {
              //跳转到首页
              //跳转到首页前 请求一次 获取当前用户信息的接口 currentAccount()
              //有账号、有激活、已启用
              //正常跳转到主界面
              let app = getApp();
              app.globalData.satoken = satoken;

              //正常登录
              currentAccount().then(responseCurrentUser => {
                if (responseCurrentUser.code == 0) {
                  app.globalData.access = access(responseCurrentUser.data);
                  app.globalData.currentUser = responseCurrentUser.data;
                  wx.setStorageSync('currentUser', responseCurrentUser.data);// 存到缓存
                  wx.reLaunch({
                    url: `/pages/home/index`
                  })
                  // typeof callBack === 'function' && callBack()
                }
              });

            } else if (this.data.bindStep == 1 && state == 5) {
              //有账户已激活已启用多用户首次登录
              //选择登录
              wx.reLaunch({
                url: `/pages/user/select/index?accountId=${accountId}`
              })
            }
            this.setData({ isLoading: false })
            wx.hideNavigationBarLoading();
            wx.hideLoading();
          })
        },
      })
    }
    this.setData({
      bindStep: 1
    })

  },
  /**
   * 联级选择 修改
   */
  cascadeChange(res: { detail: any; }) {
    const { selectedOptions } = res.detail;
    const ids = selectedOptions.map((item) => item.value)
    let select = selectedOptions.map((item) => item.label).join('/')
    if (select.length > 13) {
      select = select.slice(0, 13) + "..."
    }
    const index = res.currentTarget.dataset.index
    let newUnitList = this.data.unitList.slice(); // 先复制一份unitList数组
    newUnitList[index] = Object.assign({}, newUnitList[index], { visible: false, organizations: select, organizationIds: ids }); // 修改指定元素的visible属性

    this.setData({
      unitList: newUnitList
    });
  },
})